package com.seeqool.v1.dataviews;

import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;

import org.jfree.data.category.CategoryDataset;

import com.seeqool.v1.datamodel.SQLTable;

public class CategoryView extends BaseView implements CategoryDataset {
	
	private ArrayList<String>          rowKeys;
	private ArrayList<String>          colKeys;
	private Hashtable<String, Float[]> dataValues;
	private Hashtable<String, Integer> colIndices;
	private String					   title;

	public CategoryView(SQLTable table, int majorAxis, Integer[] minorAxes) {
		dataValues = new Hashtable<String, Float[]>();
		rowKeys    = new ArrayList<String>();
		colKeys    = new ArrayList<String>();
		colIndices = new Hashtable<String, Integer>();
		
		// Grab column names
		for (int i=0; i<minorAxes.length; i++) {
			String colName = table.getColumnName(minorAxes[i]);
			colIndices.put(colName, i);
			colKeys.add   (colName);
		}
		title = table.getColumnName(majorAxis);
		
		// Fill data values, summing duplicates
		for (int row=0; row<table.getRowCount(); row++) {
			String key=table.getValueAt(row, majorAxis).toString();
			Float[] data;
			if (dataValues.contains(key)) {
				data = dataValues.get(key);				
				for (int col=0; col<minorAxes.length; col++)
					data[col] += (Float) table.getValueAt(row, minorAxes[col]);
			} else {
				data = new Float[minorAxes.length];
				dataValues.put(key, data);
				for (int col=0; col<minorAxes.length; col++)
					data[col] = (Float) table.getValueAt(row, minorAxes[col]);
				rowKeys.add(key);
			}
		}
	}
	
	public String getTitle() { return title; }

	public int getColumnCount() { return colKeys.size(); }
	public int getRowCount   () { return rowKeys.size(); }

	@SuppressWarnings("unchecked")
	public int getColumnIndex(Comparable key) { return colIndices.get(key);  }
	@SuppressWarnings("unchecked")
	public int getRowIndex   (Comparable key) { return rowKeys.indexOf(key); }

	public Comparable<String> getColumnKey(int column) { return colKeys.get(column); }
	public Comparable<String> getRowKey   (int row)    { return rowKeys.get(row);    }

	public List<String> getColumnKeys() { return colKeys; }
	public List<String> getRowKeys   () { return rowKeys; }

	@SuppressWarnings("unchecked")
	public Number getValue(Comparable rowKey, Comparable columnKey) {
		return dataValues.get(rowKey)[colIndices.get(columnKey)];
	}

	public Number getValue(int row, int column) {
		return dataValues.get(rowKeys.get(row))[column];
	}
}
